package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishDto;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@RestController
@RequestMapping("/dish")
@Slf4j
@Transactional
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */

    @GetMapping("/page")
    public R select(int page, int pageSize, String name) {
        //分页查询
        Page<Dish> page1 = new Page<>(page, pageSize);

        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        //动态sql模糊查询
        wrapper.like(StringUtils.isNotEmpty(name), "name", name);

        dishService.page(page1, wrapper);
        //获取查询到的全部数据
        List<Dish> records = page1.getRecords();

        for (Dish record : records) {
            //根据id查找数据
            Category byId = categoryService.getById(record.getCategoryId());
            //获取name赋值给dish属性
            record.setCategoryName(byId.getName());
        }
        return R.success(page1);

    }

    /**
     * 添加
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "dish",allEntries = true)//使用注解清除redis中的数据
    public R Add(@RequestBody DishDto dishDto) {

       // redisTemplate.delete("dish_" + dishDto.getCategoryId());
        dishService.Add(dishDto);
        return R.success("添加成功");
    }

    /**
     * 停售
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R updateByIdT(Long[] ids) {

        Dish dish = new Dish();
        for (Long id : ids) {
            dish.setId(id);
            dish.setStatus(0);
            dishService.updateById(dish);
        }

        return R.success("修改成功");
    }

    /**
     * 起售
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/1")
    public R updateByIdQ(Long[] ids) {
        Dish dish = new Dish();
        for (Long id : ids) {
            dish.setId(id);
            dish.setStatus(1);
            dishService.updateById(dish);
        }

        return R.success("修改成功");
    }

    /**
     * 数据回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R selectById(@PathVariable Long id) {

        //查询数据
        Dish dish = dishService.getById(id);

        QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();

        wrapper.eq("dish_id", id);

        List<DishFlavor> list = dishFlavorService.list(wrapper);
        DishDto dto = new DishDto();
        //数据拷贝
        BeanUtils.copyProperties(dish, dto);

        dto.setFlavors(list);

        return R.success(dto);

    }

    /**
     * 修改
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "dish",allEntries = true)//修改时清理缓存
    public R update(@RequestBody DishDto dishDto) {

       /* Dish byId = dishService.getById(dishDto.getId());
        //修改前清理redis缓存
        redisTemplate.delete("dish::" + byId.getCategoryId());
        redisTemplate.delete("dish::" + dishDto.getCategoryId());*/

        dishService.updateA(dishDto);

        return R.success(null);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "dish",allEntries = true)
    public R delete(@RequestParam List<Long> ids) {

        for (Long id : ids) {
            //情空redis缓存
            Dish byId = dishService.getById(id);
            redisTemplate.delete("dish_" + byId.getCategoryId());
        }

        dishService.removeByIds(ids);

        return R.success("删除成功");
    }

    /**
     * 套餐数据回显
     *
     * @param
     * @param
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "dish",key = "#p0.categoryId")
    public R categoryById(Dish dish) {

        //先在redis中查询数据
       // List<DishDto> dishDtos = (List<DishDto>) redisTemplate.opsForValue().get("dish_" + dish.getCategoryId());
        //如果查询为空在mysql中查询或者长度为0

            QueryWrapper<Dish> wrapper = new QueryWrapper<>();

            if (dish.getCategoryId() != null) {
                wrapper.eq("category_id", dish.getCategoryId());
            }
            wrapper.eq("status", 1);
            //动态sql模糊查询
            wrapper.like(StringUtils.isNotEmpty(dish.getName()), "name", dish.getName());

            List<Dish> list = dishService.list(wrapper);

           List<DishDto> dishDtos = new ArrayList<>();

            for (Dish dishs : list) {

                QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("dish_id", dishs.getId());
                List<DishFlavor> list1 = dishFlavorService.list(queryWrapper);
                DishDto dishDto = new DishDto();
                dishDto.setFlavors(list1);
                BeanUtils.copyProperties(dishs, dishDto);
                dishDtos.add(dishDto);
            }
            //查询成功后将数据存入redis
          //  redisTemplate.opsForValue().set("dish_" + dish.getCategoryId(), dishDtos);

        return R.success(dishDtos);
    }
}
